import e, { Request, Response, NextFunction } from 'express'
import { createFile, findFileById } from './file.service'
import _ from 'lodash'
import { FileModel } from './file.model'
import fs from 'fs'
import path from 'path'

export const store = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { id: userId } = req.user
  const { postId } = req.query

  const fileInfo = _.pick(req.file, [
    'originalname',
    'filename',
    'mimetype',
    'size'
  ])

  try {
    const data = await createFile({
      ...fileInfo,
      ...req.fileMetaData,
      user_id: userId,
      post_id: +postId
    } as FileModel)

    res.send(data)
  } catch (error) {
    next(error)
  }
}

export const serve = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const { fileId } = req.params
    const { size } = req.query as { size: string }

    const file = await findFileById(+fileId)

    let filename = file.filename
    let root = 'uploads'
    let resized = 'resized'

    if (size) {
      const imageSizes = ['large', 'medium', 'small']

      if (!imageSizes.includes(size)) {
        throw new Error('FILE_NOT_FOUND')
      }

      const fileExist = fs.existsSync(
        path.join(
          root,
          resized,
          `${filename}-${size}.${file.mimetype.split('/')[1]}`
        )
      )

      if (fileExist) {
        root = root + '/' + resized
        filename = `${filename}-${size}.${file.mimetype.split('/')[1]}`
      }
    }

    res.sendFile(filename, {
      root,
      headers: {
        'Content-Type': file.mimetype
      }
    })
  } catch (error) {
    next(error)
  }
}

export const metaData = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { fileId } = req.params

  try {
    const file = await findFileById(+fileId)
    const data = _.pick(file, ['id', 'width', 'height'])
    res.send(data)
  } catch (error) {
    next(error)
  }
}
